package at.nebbl.openscotty;

/**
 *
 * @author alex.nebel
 */
public class ParseResponse implements ParseInterface{

    private final String routePattern = "headers=\"hafasOVStop\"";
    private final String datePattern = "hafasOVDate";
    private final String timePattern = "hafasOVTime";
    private final String changesPattern = "hafasOVChanges";
    private final String durationPattern = "hafasOVDuration";
    private final String stationPattern = "oebb_station_pic_81.gif";

    private StringBuilder response;

    public ParseResponse() {

    }

    public Route[] getRoutes(StringBuilder response) {
        this.response = response;

        String date, time, changes, duration, station1, station2;
        Route[] routes = new Route[3];
        for(int i=0; i<3; i++){
            StringBuilder route = getNextRoute(response);
            station1 = extractValue(route, stationPattern);
            station2 = extractValue(route, stationPattern);
            date = extractValue(route, datePattern);
            time = extractValue(route, timePattern);
            duration = extractValue(route, durationPattern);
            changes = extractValue(route, changesPattern);
            
            routes[i] = new Route(station1, station2, date, time, duration, changes);
        }
        return routes;
    }

    public String extractValue(StringBuilder route, String pattern){
        int index1, index2;
        String temp = "";
        index1 = route.indexOf(pattern);
        if(pattern.equals(timePattern)){
            route.delete(0, route.indexOf("an"));
            index1 = route.indexOf(">", index1)+1;
            index2 = route.indexOf("<", index1);
            temp += route.substring(index1, index2) + "/";
            route.delete(0, index2);
            index1 = route.indexOf(">")+1;
            index2 = route.indexOf("<", index1);
        }else{
            index1 = route.indexOf(">", index1)+1;
            index2 = route.indexOf("<", index1);
        }

        if(index2 == -1)
            index2 = route.length();
        temp += route.substring(index1, index2);
        route.delete(0, index2);
        return temp;
    }

    private StringBuilder getNextRoute(StringBuilder sb) {
        if(sb.indexOf(routePattern) == -1){
            return null;
        }else{
            int a = sb.indexOf(routePattern);
            int b = sb.indexOf(routePattern, a + 10);
            if(b == -1){
                b = sb.length();
            }
            StringBuilder temp = new StringBuilder(sb.substring(a, b));
            response.delete(0, b);
            return temp;
        }
    }
}
